<?php
/**
 * Created by PhpStorm.
 * User: ZSYK
 * Date: 2015/12/31
 * Time: 8:35
 */

namespace Icsoc\ReportBundle\Model;

use Icsoc\ReportBundle\Controller\ReportController;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ReportModel
 * @package Icsoc\ReportBundle\Model
 */
class ReportModel extends ReportController
{
    /** @var \Doctrine\DBAL\Connection  */
    protected $container;
    private $conn;
    private $logger;

    /** @var array */
    private $fixedTitle = array(
        'system' => array(
            'date'=>array('text'=>'Date', 'field'=>'date', 'sortable'=>true, 'width'=>110, 'default_show'=> true),
            'server_num'=>array('text'=>'Server Num', 'field'=>'server_num', 'sortable'=>true, 'width'=>110, 'default_show'=> true)
        ),
        'queue' => array(
            'queue_name' => array(
                'text'=>'Queue Name',
                'field'=>'queue_name',
                'sortable'=>true,
                'width'=>120,
                'default_show'=> true
            ),
            'date' => array('text'=>'Date', 'field'=>'date', 'sortable'=>true, 'width'=>110, 'default_show'=> true),
        ),
        'agent' => array(
            'ag_num' => array('text'=>'Agent Num', 'field'=>'ag_num', 'sortable'=>true, 'width'=>100, 'default_show'=> true),
            'ag_name' => array('text'=>'Agent Name', 'field'=>'ag_name', 'sortable'=>true, 'width'=>100, 'default_show'=> true),
            'date' => array('text'=>'Date', 'field'=>'date', 'sortable'=>true, 'width'=>110, 'default_show'=> true),
        ),
        'group' => array(
            'group_name' => array(
                'text'=>'Group Name',
                'field'=>'group_name',
                'sortable'=>true,
                'width'=>100,
                'default_show'=> true
            ),
            'date' => array('text'=>'Date', 'field'=>'date', 'sortable'=>true, 'width'=>110, 'default_show'=> true),
        ),
    );

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->container->get('doctrine.dbal.default_connection');
        $this->logger = $this->container->get('logger');
    }

    /**
     * @param array $param
     * @return array
     */
    public function getTitleReport($param)
    {
        $title = array();
        $reportName = isset($param['report_name']) ? $param['report_name'] : '';
        $reportType = isset($param['report_type']) ? $param['report_type'] : '';
        if (empty($reportName)) {
            return array('code'=>401, 'message'=>'报表名称不能为空');
        }
        if (($reportName == 'agent' || $reportName == 'group') && empty($reportType)) {
            return array('code'=>402, 'message'=>'报表类型不能为空');
        }
        $param['data_type'] = 'title';
        $rst = $this->processConfig($param);
        if (isset($rst['code']) && $rst['code'] == 200) {
            $title = $rst['data'];
        }
        foreach ($title as $key => $val) {
            if ($val['default_show'] == false) {
                unset($title[$key]);
            }
        }
        $title = array_merge($this->fixedTitle[$reportName], $title);

        return array('code'=>200, 'message'=>'success', 'data'=>$title);
    }

    /**
     * @param array $param
     * @return array
     */
    public function getDataReport($param)
    {
        $title = array();
        $count = array();
        $data = isset($param['data']) ? $param['data'] : array();
        $reportName = isset($param['report_name']) ? $param['report_name'] : '';
        $workTime = isset($param['work_time']) ? $param['work_time'] : '';
        if (empty($data)) {
            return array('code'=>401, 'message'=>'数据不能为空');
        }
        if (empty($reportName)) {
            return array('code'=>402, 'message'=>'报表名称不能为空');
        }
        if ($reportName == 'system' && empty($workTime)) {
            return array('code'=>403, 'message'=>'workTime不能为空');
        }
        $param['data_type'] = 'data';
        $rst = $this->processConfig($param);
        if (isset($rst['code']) && $rst['code'] == 200) {
            $title = $rst['data']['title'];
            $count = $rst['data']['count'];
        }

        $gridData = array();
        foreach ($data as $key => $value) {
            if ($reportName == 'system') {
                $value['agents'] = ceil($value['login_secs'] / $workTime);
            }
            /*if ($reportName == 'agent') {
                if (isset($value['ag_num']) && isset($value['ag_name'])) {
                    $value['agent'] = $value['ag_num'].' '.$value['ag_name'];
                }
            }*/
            foreach ($count as $k => $v) {
                $divisorPlusSum = 0;
                $divisorMinusSum = 0;
                $dividendPlusSum = 0;
                $dividendMinusSum = 0;
                if (isset($v['numerator']['plus'])) {
                    foreach ($v['numerator']['plus'] as $val) {
                        if (!isset($title[$val]['field'])) {
                            continue;
                        }
                        $divisorPlusSum += isset($value[$title[$val]['field']]) ? $value[$title[$val]['field']] : 0;
                    }
                }
                if (isset($v['numerator']['minus'])) {
                    foreach ($v['numerator']['minus'] as $val) {
                        if (!isset($title[$val]['field'])) {
                            continue;
                        }
                        $divisorMinusSum += isset($value[$title[$val]['field']]) ? $value[$title[$val]['field']] : 0;
                    }
                }
                $numerator = $divisorPlusSum - $divisorMinusSum;

                if (!isset($title[$k]['field'])) {
                    continue;
                }
                if (!isset($v['denominator'])) {
                    if ($reportName == 'agent' || $reportName == 'group') {
                        $value[$title[$k]['field']] = $numerator;
                        continue;
                    }
                    $value[$title[$k]['field']] = $numerator > 0 ? $numerator : 0 ;
                    continue;
                }

                if (isset($v['denominator']['plus'])) {
                    foreach ($v['denominator']['plus'] as $val) {
                        if (!isset($title[$val]['field'])) {
                            continue;
                        }
                        $dividendPlusSum += isset($value[$title[$val]['field']]) ? $value[$title[$val]['field']] : 0;
                    }
                }
                if (isset($v['denominator']['minus'])) {
                    foreach ($v['denominator']['minus'] as $val) {
                        if (!isset($title[$val]['field'])) {
                            continue;
                        }
                        $dividendMinusSum += isset($value[$title[$val]['field']]) ? $value[$title[$val]['field']] : 0;
                    }
                }
                $denominator = $dividendPlusSum - $dividendMinusSum;

                if (isset($v['percent']) && $v['percent'] == 1) {
                    $value[$title[$k]['field']] = '0%';
                    if ($denominator > 0) {
                        $value[$title[$k]['field']] = round($numerator / $denominator * 100, 2);
                        $value[$title[$k]['field']] = $value[$title[$k]['field']] > 100 ?
                            '100%' : $value[$title[$k]['field']].'%';
                    }
                } else {
                    $value[$title[$k]['field']] = $denominator > 0 ? round($numerator / $denominator) : $numerator;
                }
            }
            $gridData[$key] = $value;
        }

        return array('code'=>200, 'message'=>'success', 'data'=>$gridData);
    }

    /**
     * 处理配置信息
     * @param array $param
     * @return array
     */
    private function processConfig($param)
    {
        $reportName = isset($param['report_name']) ? $param['report_name'] : '';
        $reportType = isset($param['report_type']) ? $param['report_type'] : '';
        $dataType = isset($param['data_type']) ? $param['data_type'] : '';
        $defaultTitle = $this->reportItems[$reportName]['fixed_report'];
        $defaultCount = $this->calculateItems[$reportName];

        switch ($reportName) {
            case 'system':
            case 'queue':
                $connect = array(5, 10, 15, 20, 30);
                $waive = array(10, 20, 25, 30, 40);

                foreach ($connect as $v) {
                    $defaultTitle['connNum_'.$v] = array(
                        'text'=>'Conn'.$v.' Num',
                        'field'=>'conn'.$v.'_num',
                        'sortable'=>true,
                        'width'=>80,
                        'default_show'=> true
                    );
                    $defaultTitle['connRate_'.$v] = array(
                        'text'=>'Conn'.$v.' Rate',
                        'field'=>'conn'.$v.'_rate',
                        'sortable'=>true,
                        'width'=>80,
                        'default_show'=> true
                    );
                    $defaultCount['connRate_'.$v] = array(
                        'numerator' => array(
                            'plus'=> array('connNum_'.$v),
                        ),
                        'denominator' => array(
                            'plus'=> array('inboundConnNum'),
                        ),
                        'percent' => 1,
                    );
                }
                foreach ($waive as $v) {
                    $defaultTitle['lostNum_'.$v] = array(
                        'text'=>'Lost'.$v.' Num',
                        'field'=>'lost'.$v.'_num',
                        'sortable'=>true,
                        'width'=>80,
                        'default_show'=> true
                    );
                    $defaultTitle['lostRate_'.$v] = array(
                        'text'=>'Lost'.$v.' Rate',
                        'field'=>'lost'.$v.'_rate',
                        'sortable'=>true,
                        'width'=>80,
                        'default_show'=> true
                    );
                    $defaultCount['lostRate_'.$v] = array(
                        'numerator' => array(
                            'plus'=> array('lostNum_'.$v),
                        ),
                        'denominator' => array(
                            'plus'=> array('inboundAbandonTotalNum'),
                        ),
                        'percent' => 1,
                    );
                }
                break;
            case 'agent':
            case 'group':
                if ($reportType != 'halfhour') {
                    $agentStaReason = $this->get('icsoc_data.model.report')
                        ->getAgentStaReason($this->getUser()->getVccId());
                    foreach ($agentStaReason as $key => $v) {
                        $defaultTitle['agstanum'.$key] = array(
                            'text'=>$v.'次数',
                            'field'=>'agstanum'.$key,
                            'sortable'=>false,
                            'width'=>90,
                            'default_show'=> true
                        );
                        if ($reportType == 'day' || $reportType == 'month') {
                            $defaultTitle['agstaduration'.$key] = array(
                                'text'=>$v.'时长',
                                'field'=>'agstaduration'.$key,
                                'sortable'=>false,
                                'width'=>90,
                                'default_show'=>true)
                            ;
                        }
                    }
                    if (!empty($agentStaReason)) {
                        $defaultTitle['agstanum_other'] = array(
                            'text' => '其他置忙次数',
                            'field' => 'agstanum_other',
                            'sortable' => false,
                            'width' => 90,
                            'default_show' => true
                        );
                        if ($reportType == 'day' || $reportType == 'month') {
                            $defaultTitle['agstaduration_other'] = array(
                                'text' => '其他置忙时长',
                                'field' => 'agstaduration_other',
                                'sortable' => false,
                                'width' => 90,
                                'default_show' => true
                            );
                        }
                    }
                }
                break;
        }

        $title = $defaultTitle;
        $count = $defaultCount;
        $loginType = $this->getUser()->getLoginType();

        if ($loginType == 2) {
            $userRole =  $this->getUser()->getUserRole();
            try {
                $reportConfig = $this->conn->fetchColumn("SELECT report_config FROM cc_roles WHERE role_id=$userRole");
            } catch (\Exception $e) {
                $this->logger->error($e->getMessage());

                return array('code'=>400, 'message'=>'数据库执行错误');
            }
            $reportConfig = json_decode($reportConfig, true);
            $fields = isset($reportConfig[$reportName]['fixed']) ? $reportConfig[$reportName]['fixed'] : array();
            $calculate = isset($reportConfig[$reportName]['calculateItems']) ?
                $reportConfig[$reportName]['calculateItems'] : array();
            if (!empty($fields)) {
                foreach ($title as $k => $v) {
                    $title[$k]['default_show'] = in_array($k, $fields) ? true : false;
                }
            }
            if (!empty($calculate)) {
                $count = array_merge($defaultCount, $calculate);
            }
        }

        if ($dataType == 'data') {
            $title = array('title'=>$defaultTitle, 'count'=>$count);
        }

        return array('code' => 200, 'message' => 'success', 'data' => $title);
    }
}
